package cn.xspace.library.util.picture;

import android.graphics.Bitmap;
import android.graphics.Matrix;

import com.squareup.picasso.Transformation;
import com.xspace.android.xafcommon.util.LogUtil;

/**
 * Created by liuchen on 2016/10/21.
 */

public class BitmapTransformation implements Transformation {
    private int targetWidth = 500;
    private int targetHeight = 500;
    public String key;
    private static final String TAG = "BitmapTransformation";
    private Matrix m;

    public BitmapTransformation(String key) {
        this.key = key;
    }

    @Override
    public Bitmap transform(Bitmap source) {

        int sourceHeight = source.getHeight();
        int sourceWidth = source.getWidth();
        LogUtil.d(TAG, "sourceHeight " + sourceHeight + ">>>sourceWidth" + sourceWidth);
        float sampleSize = 1;
        if (sourceWidth > targetWidth || sourceHeight>targetHeight ) {
            float var6 = (float) targetWidth / (float) sourceWidth;
            float var7 = (float) targetWidth / (float) sourceHeight;
            sampleSize = var6 < var7 ? var6 : var7;
        }

        LogUtil.d(TAG, "sampleSize>>" + sampleSize);
        if (m == null) {
            m = new Matrix();
        }
//
//        final int width = src.getWidth();
//        final int height = src.getHeight();
//        final float sx = dstWidth  / (float)width;
//        final float sy = dstHeight / (float)height;
        m.postScale(sampleSize, sampleSize);
        Bitmap result = Bitmap.createBitmap(source, 0, 0, sourceWidth, sourceHeight, m, true);

//        Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, true);
        LogUtil.d("targetSize  " + result.getWidth() + "----" + result.getHeight());
        if (result != source) {
            source.recycle();
        }
        return result;
    }

    @Override
    public String key() {
        return key;
    }
}
